package com.tech.view.panel;

import com.tech.repository.entity.GoodsSort;
import com.tech.service.GoodsSortService;
import com.tech.service.impl.ServiceImplFactory;
import com.tech.util.LogProcessUtil;
import com.tech.view.common.ButtonFactory;
import com.tech.view.common.ResourcesUtil;
import com.tech.view.frame.FrameManager;
import com.tech.view.frame.MainFrame;
import org.jdesktop.swingx.VerticalLayout;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * 左侧导航面板
 */
public class LeftNavigatePanel extends JPanel {
	private final static Logger LOG = LogProcessUtil.getLogger(MainFrame.class.getName());
	private GoodsSortService goodsSortService;
	// 预设值，后面会根据窗口大小进行修改
	private int width = 120;
	private int height;
	private FrameManager frameManager;
	private List<GoodsSort> leftSort;
	private ArrayList<JButton> buttons;
	private JButton allGoodsButton;

	private JPanel contentPanel;

	public LeftNavigatePanel(int height) {
		this.height = height;
		initService();
		initComponents();
		setListeners();
		initView();
	}

	private void initService() {
		goodsSortService = ServiceImplFactory.getGoodsSortService();
	}

	private void initComponents() {
		this.frameManager = FrameManager.getInstance();
		leftSort = goodsSortService.getLeftSort();
		buttons = new ArrayList<>(leftSort.size());
		BufferedImage icon;
		for (int i = 0; i < leftSort.size(); i++) {
			if (i == 0) icon = ResourcesUtil.getImage(ResourcesUtil.Image.CHOICENESS);
			else if (i == 1) icon = ResourcesUtil.getImage(ResourcesUtil.Image.HOT);
			else icon = null;
			buttons.add(ButtonFactory.createIconButton(width, 35, leftSort.get(i).getSsortname(), icon, SwingConstants.LEFT));
		}

		allGoodsButton = ButtonFactory.createIconButton(width, 35, "全部书籍", ResourcesUtil.getImage(ResourcesUtil.Image.ALL_GOODS), SwingConstants.LEFT);
	}

	private void initView() {
		setLayout(new BorderLayout());
		setPreferredSize(new Dimension(width, height));

		contentPanel = new JPanel(new VerticalLayout());
		buttons.forEach(contentPanel::add);
		add(contentPanel);

		add(allGoodsButton, BorderLayout.SOUTH);
	}

	private void setListeners() {
		for (int i = 0; i < buttons.size(); i++) {
			Integer sid = leftSort.get(i).getSid();
			buttons.get(i).addActionListener(e -> {
				// TODO 根据sid更改推荐商品
			});
		}

		allGoodsButton.addActionListener(e -> {
			// TODO 显示全部书籍
		});
	}

	@Override
	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	@Override
	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}
}
